package com.bbm.communitysystem.controller;


import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.domain.Family;
import com.bbm.communitysystem.domain.dto.FamilyDto;
import com.bbm.communitysystem.domain.vo.FamilyVo;
import com.bbm.communitysystem.service.IFamilyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bbm
 * @since 2025-02-21
 */
@Tag(name = "家庭")
@RestController
@RequestMapping("/family")
@RequiredArgsConstructor
public class FamilyController {

    private final IFamilyService familyService;

    @Operation(summary = "创建家庭")
    @PostMapping("")
    public R createFamily(@RequestBody FamilyDto familyDto) {
        FamilyDto family = familyService.createFamily(familyDto);
        if (family == null) {
            return R.error("创建失败");
        }
        return R.ok("创建成功");
    }

    @Operation(summary = "获取家庭")
    @GetMapping("/{id}")
    public R getFamilyById(@PathVariable Long id) {
        Family family = familyService.getById(id);
        if (family == null) {
            return R.error("没有这个家庭");
        }
        FamilyVo familyVo = BeanUtil.copyProperties(family, FamilyVo.class);
        return R.ok(familyVo);
    }

    @Operation(summary = "更新家庭")
    @PutMapping("/")
    public R updateFamily(@RequestBody FamilyDto familyDto) {
        Family family = BeanUtil.copyProperties(familyDto, Family.class);
        family.setUpdateTime(System.currentTimeMillis() + "");
        boolean b = familyService.updateById(family);
        if (b) {
            return R.error("更新失败");
        }
        return R.ok("更新成功");
    }

    @Operation(summary = "删除家庭")
    @DeleteMapping("/{id}")
    public R deleteFamily(@PathVariable Long id) {
        boolean isDeleted = familyService.removeById(id);
        if (!isDeleted) {
            return R.error("删除失败");
        }
        return R.ok("删除成功");
    }


    @Operation(summary = "获取家庭列表")
    @GetMapping("/")
    public R getFamilyList() {
        return R.ok(familyService.list());
    }

}
